<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    .wrap {
      width: 80%;
      margin: 20px auto;

    }

    h1 {
      text-align: center;
      margin: 30px 0;
    }

    table {
      width: 100%;
    }

    td {
      text-align: center;
      border-bottom: 1px solid #e5e5e5;
    }

    td img {
      width: 100px;
      height: 100px;
    }

    td input {
      width: 60px;
      text-align: center;
    }

    .count {
      margin: 20px auto;
    }

    thead {
      background: #e5e5e5;
    }

    .cart_foot {
      width: 80%;
      height: 60px;
      background: skyblue;
      position: fixed;
      bottom: 0;
      left: 50%;
      margin-left: -40%;
      display: flex;
      justify-content: space-between;
      line-height: 60px;
      font-size: 30px;
    }

    .cart_foot>div:nth-child(2) {
      display: flex;

    }

    #order {
      width: 140px;
      height: 60px;
      line-height: 60px;
      background: red;
      color: white;
      text-align: center;
      margin-left: 20px;
      cursor: pointer;
    }
  </style>
</head>

<body>
  <div class="wrap">
    <h1>购物车页面</h1>
    <div class="count">全部商品：34</div>
    <table>
      <thead>
        <tr>
          <th>全选：<input type="checkbox" id="allCheck"></th>
          <th>图片</th>
          <th>名称</th>
          <th>描述</th>
          <th>价格</th>
          <th>数量</th>
          <th>小计</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody id="mybody">
        <!-- <tr>
          <td><input type="checkbox"></td>
          <td><img src="" alt=""></td>
          <td>名称</td>
          <td>描述</td>
          <td>价格</td>
          <td>数量</td>
          <td>小计</td>
          <td>
            <button>删除</button>
          </td>
        </tr> -->
      </tbody>
    </table>
    <h1 class="tips">
      购物车 空空如也！！ <a href="./index.html">去购物吧</a>
    </h1>
    <div class="cart_foot">
      <div>
        <a href="#">删除选中商品</a>
        <a href="#">清空购物车</a>
      </div>
      <div>
        <span>已选择 <span style="color:red;" class="proNum">1</span>商品</span>
        <span>总价: <span style="color:red;" class="myTotal">88</span></span>
        <span id="order">去结算</span>
      </div>
    </div>
  </div>
  <script src="./jquery-3.4.1.min.js"></script>
  <script>
    // 获取购物车列表接口
    function loadCartList() {
      $.ajax({
        url: "http://127.0.0.1:3000/cart/cartAll",
        type: "post",
        data: {
          uid: localStorage.uid,
          token: localStorage.token
        },
        success: function (res) {
          // ---------------------------------
          if (res.length != 0) {
            $(".tips").hide()
            $("table").show()
            console.log(res)
            var str = ``
            var num = 0; //总数量
            $.each(res, function (index, ele) {
              num += Number(ele.num)
              str += ` <tr>
              <td><input type="checkbox" class="cks" onchange="check('${ele._id}','${ele.ischeck}')"  ${ele.ischeck == "true" ? "checked" : ''}></td>
              <td><img src="./images/${ele.img}.jpg" alt=""></td>
              <td>${ele.pname}</td>
              <td>${ele.des}</td>
              <td>${ele.price}</td>
              <td>
                <button onclick="minAndPlus('${ele._id}','min',this)">-</button>
                <input  class="cnum" type="text" value="${ele.num}"  />
                <button onclick="minAndPlus('${ele._id}','plus',this)">+</button>
              </td>
              <td>${(Number(ele.price) * Number(ele.num)).toFixed(2)}</td>
              <td>
                <button onclick="del('${ele._id}')">删除</button>
              </td>
            </tr>`
            })
            $("#mybody").html(str)
            $(".count").html("全部商品：" + num)
            testCheck()//判断是否全选
            Total()// 计算选择的数量和总价函数
          } else {
            $(".tips").show()
            $("table").hide()
          }
          // -------------------------------------
          if (res.err) {
            alert(res.err)
            location.href = "./login.html"
          }
        }
      })
    }
    loadCartList()
    //删除购物车商品
    function del(id) {
      var flag = confirm("确认要删除吗，在考虑考虑?");
      if (flag) {
        $.ajax({
          url: "http://127.0.0.1:3000/cart/delCart",
          type: "post",
          data: { id: id },
          success: function () {
            loadCartList()
          }
        })
      }
    }
    // 更改数量接口
    function minAndPlus(id, status, that) {
      var num = 0;
      if (status == "min") {
        num = Number($(that).next().val())
        num--
        if (num < 1) {
          num = 1
        }
      }
      if (status == "plus") {
        num = Number($(that).prev().val())
        num++
      }
      $.ajax({
        url: "http://127.0.0.1:3000/cart/updateNum",
        type: "post",
        data: {
          id: id,
          num: num
        },
        success: function () {
          loadCartList()
        }
      })
    }
    // 单选方法
    function check(id, ischeck) {
      console.log(ischeck)
      var mycheck = ischeck == "true" ? "false" : "true";
      $.ajax({
        url: "http://127.0.0.1:3000/cart/check",
        type: "post",
        data: {
          id: id,
          ischeck: mycheck
        },
        success: function (res) {
          loadCartList()
        }
      })
    }
    // 全选功能
    $("#allCheck").change(function () {
      console.log($(this).prop("checked"))  //！！！！！获取checked 属性 使用jq的prop() 方法
      var check = $(this).prop("checked").toString();
      $.ajax({
        url: "http://127.0.0.1:3000/cart/allCheck",
        type: "post",
        data: {
          uid: localStorage.uid,
          allCheck: check
        },
        success: function () {
          loadCartList()
        }
      })
    })
    // 检测是否需要全选
    function testCheck() {
      var flag = true;
      // 循环所有的单选框 
      $.each($(".cks"), function (index, ele) {
        if (ele.checked == false) { //只要有一个单选框是false 锁 变为false
          flag = false;
        }
      })

      $("#allCheck").prop("checked", flag);

    }
    //选中商品数量 和选择价格的计算
    function Total() {
      var num = 0;//选中商品的数量
      var totalPirce = 0;//选中商品的总价
      $.each($(".cks"), function (index, ele) {
        if (ele.checked) {
          num += Number($(ele).parent().parent().find(".cnum").val())
          totalPirce += Number($(ele).parent().parent().children().eq(6).html())
        }
      })
      $(".proNum").html(num)
      $(".myTotal").html("￥" + totalPirce)
    }
  </script>
</body>

</html>